<template>
  <div class="root-layout">
    <!-- titleBar -->
    <u-navbar
      height="50"
      title="修改个人资料"
      @leftClick="onBack"
      :autoBack="true"
    ></u-navbar>
    <!-- content -->
    <div class="content-layout">
      <u-line></u-line>
      <div class="menu-item-layout">
        <img
          src="@/static/icon_user.png"
          style="width: 25px; height: 25px"
          alt=""
        />
        <view class="text">用户名</view>
        <div class="right">
          <u--input
            style="font-size: 14px"
            placeholder="请输入用户名"
            border="none"
            :maxlength="20"
            v-model="fromData.realName"
            inputAlign="right"
            :clearable="true"
          ></u--input>
        </div>
      </div>
      <u-line></u-line>
      <div class="menu-item-layout">
        <img
          src="@/static/icon_location.png"
          style="width: 25px; height: 25px"
          alt=""
        />
        <view class="text">常驻城市</view>
        <div class="city-right-layout" @click="isShowAddressWindow = true">
          <view :class="isSelected() ? 'text-color' : 'hint-text-color'">
            {{ isSelected() ? getSelectAddress() : "请选择常驻城市" }}</view
          >
          <u-icon size="20" name="arrow-right"></u-icon>
        </div>
      </div>
      <u-line></u-line>
      <div class="menu-item-layout">
        <view class="text">手机验证码</view>
        <view style="flex: 2; margin-left: 10px; margin-right: 10px">
          <u--input
            type="number"
            placeholder="请输入验证码"
            border="none"
            v-model="fromData.code"
            :clearable="true"
            maxlength="6"
          ></u--input>
        </view>
        <div class="code-layout" @click="getCode()">
          <view style="color: #f05f5d">{{ codeBtnName }}</view>
        </div>
      </div>
      <u-line></u-line>
      <!-- 底部按鈕 -->
      <div class="bottom-button">
        <button class="cancel-button" @click="cancel">取消</button>
        <button class="save-button" @click="checkSmsCode">保存</button>
      </div>
    </div>
    <!--  地区选择 -->
    <u-picker
      ref="areaPicker"
      :defaultIndex="defaultIndex"
      :show="isShowAddressWindow"
      :columns="columns"
      @cancel="isShowAddressWindow = false"
      @change="changeHandler"
      @confirm="onAddressConfirm"
    ></u-picker>
  </div>
</template>

<script>
import { PROVINCE, CITY } from "../../common/addressData";
import { msg } from "../../common/js/util";
import userApi from "@/api/user";
import mineApi from "@/api/mine";
import passData from "@/api/requstUtil";

export default {
  data() {
    return {
      fromData: {
        realName: "",
        province: "", // 省
        city: "", // 市
        code: "",
      },
      defaultIndex: [0, 0],
      isShowAddressWindow: false,
      PROVINCE,
      CITY,
      provinceList: [],
      cityList: [],
      columns: [PROVINCE, CITY[0]],
      provinceIndex: 0,
      cityIndex: 0,
      intervalId: null,
      countdown: 60, // 倒计时60s
      isStartGetCode: false,
      codeBtnName: "获取验证码",
      phone: "",
    };
  },
  onLoad(option) {
    const eventChannel = this.getOpenerEventChannel();
    let that = this;
    eventChannel.on("acceptMineData", function (data) {
      // 设置地区默认值
      that.setAea(data)
      let residentCityArr = data.residentCity.split("-");
      let province = residentCityArr[0];
      let city = residentCityArr.length > 1 ? residentCityArr[1] : "";
      that.fromData = {
        realName: data.realName,
        phone: data.phone,
        imgBsnNo: data.imgBsnNo,
        userId: data.userId,
        province,
        city,
      };
    });
  },
  methods: {
    setAea(data) {
      let residentCityArr = data.residentCity.split("-");
      let province = residentCityArr[0];
      let city = residentCityArr.length > 1 ? residentCityArr[1] : "";
      for (let i = 0; i < this.PROVINCE.length; i++) {
        if (this.PROVINCE[i] === province) {
          this.provinceIndex = i;
        }
      }
      if (city) {
        for (let i = 0; i < this.CITY[this.provinceIndex].length; i++) {
          if (this.CITY[this.provinceIndex][i] === city) {
            this.cityIndex = i;
          }
        }
      }
      this.provinceList = [...this.PROVINCE]
      let element = this.provinceList.splice(this.provinceIndex, 1)[0];
      this.provinceList.splice(0, 0, element);
      this.cityList = [...this.CITY]
      let ele = this.cityList.splice(this.provinceIndex, 1)[0];
      this.cityList.splice(0, 0, ele);
      this.columns = [this.provinceList, this.cityList[0]]
      this.defaultIndex = [0, this.cityIndex]
      // 重置为0
      this.provinceIndex = 0
    },
    getSelectAddress() {
      if (this.fromData.city) {
        return `${this.fromData.province}-${this.fromData.city}`;
      } else {
        return `${this.fromData.province}`;
      }
    },
    isSelected() {
      return this.fromData.province || this.fromData.city;
    },
    // 地址选择监听
    changeHandler(e) {
      console.log(3333, e)
      const { columnIndex, index, picker } = e;
      if (columnIndex == 0) {
        // 切换省份
        this.provinceIndex = index;
        picker.setColumnValues(1, this.cityList[this.provinceIndex]);
      } else if (columnIndex == 1) {
        // 切换市区
        this.cityIndex = index;
      }

    },
    // 地区选择确定
    onAddressConfirm() {
      this.isShowAddressWindow = false;
      this.fromData.province = this.provinceList[this.provinceIndex];
      this.fromData.city = this.cityList[this.provinceIndex][this.cityIndex];
      // 确定选择后恢复默认index
      this.provinceIndex = 0;
      this.cityIndex = 0;
    },
    // 返回上一页
    onBack() {
      uni.navigateBack();
    },
    // 获取验证码
    async getCode() {
      if (!this.isStartGetCode) {
        console.log("获取验证码", this.fromData.phone);
        let param = {
          phone: this.fromData.phone,
          sendSystem: "MINIP",
          smsCodeType: "USER_UPDATE",
          smsCodeTemplate: "22345",
          tenantId: "gysk",
        };
        try {
          const res = await userApi.loginSms(param);
          let data = passData(res);
          if (data) {
            console.log(data);
            this.startCountDown();
          }
        } catch (e) {
          console.log(e);
        }
      }
    },
    // 开始倒计时
    startCountDown() {
      if (this.intervalId) {
        return;
      }
      this.isStartGetCode = true;
      this.countdown = 60;
      this.codeBtnName = "60s";
      this.intervalId = setInterval(() => {
        this.countdown--;
        this.codeBtnName = `${this.countdown}s`;
        if (this.countdown <= 0) {
          this.codeBtnName = "重新获取";
          this.isStartGetCode = false;
          clearInterval(this.intervalId);
          this.intervalId = null;
        }
      }, 1000);
    },
    // 取消
    cancel() {
      uni.navigateTo({
        url: `/pages/index/index?value=1`,
      });
    },
    // 短信验证码校验
    async checkSmsCode() {
      const { realName, province, city, code, phone, imgBsnNo, userId } =
        this.fromData;
      if (!realName) return msg("请输入用户名");
      if (!province) return msg("请选择常驻城市");
      if (!code) return msg("请输入验证码");
      let param = {
        phone: phone,
        realName,
        imgBsnNo,
        userId,
        updateType: ' INFO',
        residentCity: city ? `${province}-${city}` : province,
      };
      try {
        const res = await userApi.checkSmsCode({
          phone,
          smsCode: code,
          smsCodeType: "USER_UPDATE",
        });
        let data = passData(res);
        if (data) {
          console.log(445, data);
          param.smsCodeToken = data.smsToken;
          this.save(param);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 保存
    async save(param) {
      try {
        const res = await mineApi.postUpdateData(param);
        let data = passData(res);
        if (data) {
          msg("保存成功");
          uni.navigateTo({
            url: `/pages/index/index?value=1`,
          });
        }
      } catch (e) {
        console.log(e);
      }
    },
  },
  onUnload() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
  },
};
</script>
<style lang="scss" scoped>
.root-layout {
  width: 100vw;
  height: 100vh;
  overflow: hidden;

  .content-layout {
    height: calc(100vh - 50px);
    width: 100%;
    margin-top: 50px;
    overflow-x: hidden;
    overflow-y: auto;
    position: relative;

    .menu-item-layout {
      width: calc(100% - 20px) !important;
      background: white !important;
      padding: 10px;
      display: flex;
      flex-direction: row;
      height: 40px;
      align-items: center;
      position: relative;

      .text {
        margin-left: 10px;
        font-size: 14px;
      }

      .right {
        position: absolute;
        right: 0%;
        margin-right: 10px;
      }

      .city-right-layout {
        flex: 1;
        margin-left: 10px;
        font-size: 14px;
        align-items: center;
        justify-content: right;
        display: flex;
        flex-direction: row;
      }

      .code-layout {
        flex: 1;
        background-color: white;
        border: solid #f05f5d 1px;
        border-radius: 50px;
        padding-top: 5px;
        text-align: center;
        font-size: 14px;
        padding-bottom: 5px;
        padding-left: 10px;
        padding-right: 10px;
      }
    }

    // 底部按鈕
    .bottom-button {
      width: 100%;
      display: flex;
      flex-direction: row;
      position: absolute;
      bottom: 0;
      margin-bottom: 10px;

      .cancel-button {
        width: 40%;
        background: white;
        color: #f05f5d;
        font-size: 14px;
        border-radius: 10px;
        height: 36px;
        border: solid 1px #f05f5d;
      }

      .save-button {
        width: 40%;
        background: #f05f5d;
        font-size: 14px;
        color: white;
        border-radius: 10px;
        height: 36px;
        border: solid 1px #f05f5d;
      }
    }
  }

  .hint-text-color {
    color: rgb(192, 196, 204);
  }

  .text-color {
    color: black;
  }
}
</style>
